using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using CustomSecurity;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (Label lbl = (Label)Master.FindControl("lblHeaderTitle"))
        {
            lbl.Text = "Nu-Trax Login";
        }
    }
    protected void NuTrackerLogin_Authenticate(object sender, AuthenticateEventArgs e)
    {
        using (AppUser oAppUser = new AppUser())
        {
            Hashtable oInfo = oAppUser.Login(NuTrackerLogin.UserName, NuTrackerLogin.Password, Request.ServerVariables["Local_Addr"], DateTime.UtcNow);
            e.Authenticated = (oInfo != null);
            if (e.Authenticated)
            {
                int nAppUserID = Convert.ToInt32(oInfo["AppUserID"]);


                ArrayList aRole = new ArrayList();
                using (DataTable dt = oAppUser.GetAppRoles(nAppUserID))
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        aRole.Add(dr["AppRoleName"].ToString());
                    }
                }

                StringBuilder sbRoles = new StringBuilder();
                foreach (string sRole in aRole)
                {
                    sbRoles.AppendFormat("|{0}", sRole);
                }
                if (sbRoles.Length > 0)
                    sbRoles.Remove(0, 1);

                if (oInfo != null)
                {
                    CustomIdentity identity = new CustomIdentity(nAppUserID, true, true, string.Format("{0} {1}", oInfo["FirstName"], oInfo["LastName"]), Convert.ToString(oInfo["EmailAddress"]), Request.UserHostAddress, sbRoles.ToString());
                    CustomPrincipal principal = new CustomPrincipal(identity, aRole);

                    CustomAuthentication.RedirectFromLoginPage(identity);
                }
            }
        }
    }
    protected void NuTrackerLogin_LoginError(object sender, EventArgs e)
    {

    }
    protected void NuTrackerLogin_LoggedIn(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }
}
